package com.jolink.omiis.commons.mongodb.impl;

import java.io.File;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jolink.omiis.commons.mongodb.preferences.IPreferenceKeys;
import com.jolink.omiis.commons.mongodb.util.ConfigUtils;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongodbManager {

	private static Logger logger = LoggerFactory.getLogger(MongodbManager.class);

	public static void main(String[] args) {

	}

	private static MongodbManager instance = null;

	private MongodbManager() {
		try {
			Properties mongodbProp = ConfigUtils.loadConfig(new File(IPreferenceKeys.MONGODB_CONFIG_PATH));
			logger.info("Mongodb配置信息：" + mongodbProp);
			String host = mongodbProp.getProperty("host", IPreferenceKeys.MONGODB_DEFAULT_HOST);
			String port = mongodbProp.getProperty("port", IPreferenceKeys.MONGODB_DEFAULT_PORT);
			String databaseName = mongodbProp.getProperty("databaseName", IPreferenceKeys.MONGODB_DEFAULT_DATABASENAME);
			mongoClient = new MongoClient(host, Integer.parseInt(port));
			mdb = mongoClient.getDatabase(databaseName);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static MongodbManager getInstance() {
		if (instance == null) {
			instance = new MongodbManager();
		}
		return instance;
	}

	private static MongoClient mongoClient = null;

	private static MongoDatabase mdb = null;

	public static MongoClient getMongoClient() {
		return mongoClient;
	}

	public static MongoDatabase getMongoDatabase(String databaseName) {
		return getMongoClient().getDatabase(databaseName);
	}

	public static MongoDatabase getMongoDatabase() {
		return mdb;
	}

	public static MongoCollection getMongoCollection(String collectionName) {
		return getMongoDatabase().getCollection(collectionName);
	}

	public static void shutdown() {
		if (mongoClient != null) {
			mongoClient.close();
		}
	}
}
